package dao;

import model.StudentScholarship;
import util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StudentScholarshipDao {

    /**
     * 添加新的奖学金记录到数据库
     * @param sch 传入的奖学金对象
     * @return 插入成功返回true，否则false
     */
    public boolean addScholarship(StudentScholarship sch) {
        String sql = "INSERT INTO scholarship (name, criteria) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, sch.getName());
            ps.setString(2, sch.getCriteria());
            return ps.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 获取所有奖学金信息列表
     * @return 返回奖学金对象的列表
     */
    public List<StudentScholarship> getAll() {
        List<StudentScholarship> list = new ArrayList<>();
        String sql = "SELECT id, name, criteria  FROM scholarship";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {

            // 遍历结果集，封装成奖学金对象并加入列表
            while (rs.next()) {
                StudentScholarship sch = new StudentScholarship();
                sch.setId(rs.getInt("id"));  // 奖学金ID
                sch.setName(rs.getString("name"));  // 奖学金名称
                sch.setCriteria(rs.getString("criteria"));  // 申请条件
                list.add(sch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }



    public boolean deleteByName(String name) {
        String sql = "DELETE FROM scholarship WHERE name = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, name);
            return stmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean updateByName(String name, String newRequirement) {
        String sql = "UPDATE scholarship SET criteria = ?WHERE name = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, newRequirement);
            stmt.setString(2, name);
            return stmt.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
